package com.qadev.appergodic.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qadev.appergodic.bean.Performance;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import static java.lang.Thread.sleep;

/**
 * 性能监控
 * Created by wjp on 2019/8/8.
 */
@Slf4j
@Data
public class PerformanceUtil implements Runnable {

    private String serverName;
    private int times;

    public PerformanceUtil(String serverName,int times){
        this.serverName=serverName;
        this.times=times;
    }

    public PerformanceUtil(String serverName){
        this.serverName=serverName;
    }

    private volatile boolean runnerFlag= true;
    public void stopTask() {
        runnerFlag = false;
        log.info("监控性能的线程结束.........");
    }

    public void run() {
        Process p = null;
        try {
            // 如果时间大于0  ，按传入时间频率输出数据，否则按默认5秒输出
            if(times>0){
                p = Runtime.getRuntime().exec("adb shell top -d "+times+" |grep "+serverName);
            }else {
                //p = Runtime.getRuntime().exec("adb shell top '|grep "+serverName+"'");
                p = Runtime.getRuntime().exec("adb shell top |grep "+serverName);
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
        while(runnerFlag){

            try {
                System.out.println("开启cpu监控。。。。");

                BufferedReader br2 = null;
                String line = null;
                InputStream is = null;
                InputStreamReader isReader = null;

                Performance performance = new Performance();

                JSONArray jsonArray = new JSONArray();
                List<String> cpus = new ArrayList<>();
                List<String> vss = new ArrayList<>();
                List<String> rss = new ArrayList<>();
                List<String> timeLine = new ArrayList<>();
                List<String> performances = Arrays.asList("PID", "PR", "CPU", "S", "THR", "VSS", "RSS", "PCY", "UID", "Name");


                try {


                    is = p.getInputStream();
                    isReader = new InputStreamReader(is, "utf-8");
                    br2 = new BufferedReader(isReader);
                    // 读取每行数据内容：10564  3   0% S    65 2022076K 142948K  fg u0_a224  com.houbank.paydayloan   然后分割取出cpu利用率
                    while ((line = br2.readLine()) != null) {
                        if (line.length() > 0) {
                            //log.info("读取原始的监控信息内容：{}",line);

                            JSONObject jsonObject = new JSONObject();
                            ;
                            //System.out.println("每行数据内容："+line.replace(" ",","));
                            /**
                             * 按照空格分割，将空内容剔除
                             * 分割后如果不为空，分别存放如 performances 中去"PID","PR","CPU","S","THR","VSS","RSS"
                             *
                             * */
                            int y = 0;
                            for (int i = 0; i < line.split(" ").length; i++) {

                                if(line.split(" ")[i].length()>0 && y< performances.size()){
                                    // 对cpu  内存进行单位换算处理
                                    String perf = performances.get(y);
                                    String perfValue = line.split(" ")[i];
                                    if("CPU".equals(perf)){
                                        jsonObject.put(perf,perfValue.replace("%",""));  // 去掉cpu的%
                                    }else if("RSS".equals(perf) || "VSS".equals(perf)){
                                        Integer mem = Integer.parseInt(perfValue.replace("K",""))/1024 ;
                                        jsonObject.put(perf,mem);
                                    }else{
                                        jsonObject.put(perf,perfValue);
                                    }

                                    y++;
                                }
                            }
                            log.info("将app监控的性能数据转换为json：{}", jsonObject);
                            if(serverName.equals(jsonObject.getString("Name"))) {
                                cpus.add(jsonObject.getString("CPU"));
                                rss.add(jsonObject.getString("RSS"));    // 去掉 单位k
                                vss.add(jsonObject.getString("VSS"));
                                timeLine.add(DateUtil.formatDate(new Date(), "HH:mm:ss"));
                                performance.setCpu(cpus);
                                performance.setRss(rss);
                                performance.setVss(vss);
                                performance.setTimeLine(timeLine);
                                performance.setDate(DateUtil.formatDate(new Date(), "yyyy-MM-dd"));
                                jsonArray.add(jsonObject);
                            }


                        }


                    }
                } catch (IOException e) {
                    System.out.println("异常跳出时数据内容：" + line);
                } finally {
                    if (isReader != null) {
                        try {
                            isReader.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                        }
                    }

                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                        }
                    }

                    if (br2 != null) {
                        try {
                            br2.close();
                        } catch (IOException e) {
                            // TODO
                        }
                    }
                }


                System.out.println("数据内容：" + cpus);
                sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

    }
}
